﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BattleThis.Core;
using System.Web.Security;
using BattleThis.Helpers;

namespace BattleThis.Controllers
{
	[Authorize]
    public class LobbyController : Controller
    {

		#region Variablen
		public const string IndexAction = "Index";
		public const string CreateAction = "Create";
		public const string LoadAction = "Load";
		public const string JoinAction = "Join";
		public static readonly ReflectedControllerDescriptor Info = new ReflectedControllerDescriptor( typeof( LobbyController ) );
		#endregion

		#region Properties
		#endregion

		#region Methoden

		[ActionName( IndexAction )]
		public ActionResult Index()
		{


			var service = this.GetGameService();
			var games = service.Load();

			return View( games );
		}

		[ActionName( CreateAction ), HttpGet()]
		public ActionResult Create()
		{
			var service = this.GetMapService();
			var maps = service.LoadMaps();
			var model = new GameStage();

			//todo Hulk overide the tostring of maps methode to get more infos like player count, ...
			model.Maps = maps.Select( x => new SelectListItem { Text = x.Name, Value= x.Name } );

			return View( model );
		}

		[ActionName( CreateAction ), HttpPost()]
		public ActionResult Create( GameStage model )
		{
			var gameService = this.GetGameService();

			gameService.Create( model.Name, model.Maps.Where(x=> x.Selected).Single().Value.ToString() );

			return RedirectToAction( IndexAction );
		}

		[ActionName( LoadAction )]
		public ActionResult Load( int id )
		{
			var service = this.GetGameService();
			var game = service.Load( id );
			var context = new GameContext( game );

			if( !game.IsReady() ) return Redirect( IndexAction );

			this.HttpContext.SetGameContext( context );
			this.HttpContext.User = game.Players.First();

			return RedirectToAction ( GameController.IndexAction, GameController.Info.ControllerName );
		}

		[ActionName( JoinAction )]
		public ActionResult Join ( int id )
		{
			var gameService = this.GetGameService();
			var playerService = this.GetPlayerService();

			var game = gameService.Load( id );
			var player = playerService.Load(  this.User.Identity.Name );

			game.Join( player );

			return RedirectToAction( IndexAction );
		}

		/// <summary>
		/// Gets the game.
		/// </summary>
		/// <returns></returns>
		private GameService GetGameService()
		{
			GameService service = new GameService();
			
			return service;
		}

		/// <summary>
		/// Gets the map-service.
		/// </summary>
		/// <returns></returns>
		private MapService GetMapService()
		{
			MapService service = new MapService();

			return service;
		}

		/// <summary>
		/// Gets the player service.
		/// </summary>
		/// <returns></returns>
		private PlayerService GetPlayerService()
		{
			return new PlayerService();
		}

		#endregion

    }
}
